<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script>
import wx from "weixin-js-sdk";
import { mapMutations, mapState, mapActions } from "vuex";
import qs from "qs";
import { post } from "./js/utils";
import { Dialog, Loading, Toast } from "vant";
import wxJSFn from "@/js/wxJSFn";
export default {
  name: "App",
  async created() {
    //测试用
    //外部浏览器跳过
    let viewer = window.navigator.userAgent.toLowerCase();
    if (viewer.match(/MicroMessenger/i) == "micromessenger") {
      try {
        //微信浏览器
        let jsApiTicket = await post("/mp/getJsapiConfig", {
          url: encodeURI(window.location.href),
        });

        //1、判断是否没有授权，没授权则重定向授权
        let redirect = await this.redirectOrNot(jsApiTicket);
        //2、若是通过用户，则获取用户信息
        if (redirect) {
          const resQuery = qs.parse(
            window.location.href.split("?")[1].split("#")[0]
          );
          let user = await post("/mp/oauth2getAccessToken", {
            code: resQuery.code,
          });
          console.log("user", user);
          if (user != null) {
            this.loadUser(user);
          } else {
            // this.setUserId(this.$store.state.userInfo.openId);
            console.log("userId", this.$store.state.userId);
            if (this.$store.state.userId) {
            } else {
              let auth = await this.redirectAuth(jsApiTicket);
              if (auth) {
                return;
              }
            }
          }
          //3、url添加调试代码
          this.debug();
          //4、添加业务
          // await this.doBusiness(resQuery, jsApiTicket);
          //分享
          wx.config({
            debug: false,
            beta: true,
            appId: jsApiTicket.appId,
            timestamp: jsApiTicket.timestamp,
            nonceStr: jsApiTicket.nonceStr,
            signature: jsApiTicket.signature,
            jsApiList: [
              "checkJsApi",
              "updateAppMessageShareData",
              "onMenuShareAppMessage",
              "openLocation",
              "hideMenuItems",
              "showMenuItems",
              "updateTimelineShareData",
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
              "scanQRCode",
              "closeWindow",
              "getLocation",
              "chooseWXPay",
            ],
          });
          let self = this;
          wx.ready(function () {
            wxJSFn.hideShareMenu();
            self.setAppData({
              resQuery,
              jsApiTicket,
            });
          });
        }
      } catch (error) {
        console.log(error);
        Dialog.alert({
          title: "提示",
          message: "数据初始化失败~",
        })
          .then(() => {
            // on confirm
          })
          .catch(() => {
            // on cancel
          });
      }
    }
  },
  methods: {
    ...mapMutations({
      setJsapiTicket: "setJsapiTicket",
      setUserId: "setUserId",
      setSubscribe: "setSubscribe",
      setShareParams: "setShareParams",
      setActivityMsg: "setActivityMsg",
      setUserInfo: "setUserInfo",
      setSupInfoMy: "activity/setSupInfoMy",
      setAvListMy: "activity/setAvListMy",
      pageReady: "activity/pageReady",
      setAvList: "activity/setAvList",
      setSupInfo: "activity/setSupInfo",
      setAppData: "setAppData",
      setStaffInfo: "setStaffInfo",
    }),
    redirectOrNot(jsApiTicket) {
      return new Promise((resolve, reject) => {
        const baseUrl = window.location.href;
        try {
          const resQuery = qs.parse(
            window.location.href.split("?")[1].split("#")[0]
          );
          //重定向服务器
          if (
            typeof resQuery == "undefined" ||
            typeof resQuery.code == "undefined" ||
            resQuery.code == null
          ) {
            console.log("重定向");
            const redirectUrl = encodeURIComponent(baseUrl);
            const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${jsApiTicket.appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
            window.location.href = dst;
            resolve(0);
          }
          resolve(1);
        } catch (error) {
          const redirectUrl = encodeURIComponent(baseUrl);
          const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${jsApiTicket.appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
          window.location.href = dst;
          resolve(0);
        }
      });
    },
    redirectAuth(jsApiTicket) {
      return new Promise((resolve, reject) => {
        const baseUrl = window.location.href;
        const resQuery = qs.parse(
          window.location.href.split("?")[1].split("#")[0]
        );
        console.log("授权后resQuery", resQuery);
        let regStrArr = [];

        if (resQuery.code) {
          let str = qs.stringify({
            code: resQuery.code,
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr}|${str})`);
        }
        if (resQuery.state) {
          let str = qs.stringify({
            state: resQuery.state,
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr}|${str})`);
        }
        if (resQuery.from) {
          let str = qs.stringify({
            from: resQuery.from,
          });
          let encodeStr = encodeURIComponent(str);
          regStrArr.push(`(&${str}|&${encodeStr}|${str})`);
        }
        let regStr = regStrArr.join("|");

        let reg3 = new RegExp(regStr, "g");
        let url1 = baseUrl.replace(reg3, "");
        // url1 = url1.replace(reg2, "");
        const redirectUrl = encodeURIComponent(url1);
        const dst = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${jsApiTicket.appId}&redirect_uri=${redirectUrl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;
        window.location.href = dst;
        resolve(1);
      });
    },
    loadUser(user) {
      this.setUserInfo(user);
    },
    debug: function () {
      let { debug } = qs.parse(
        window.location.href.split("#")[0].split("?")[1]
      );
      if (debug) {
        localStorage.clear();
        sessionStorage.clear();
      }
    },
  },
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  /* text-align: center; */
  color: #2c3e50;
}
@font-face {
  font-family: SiYuanHeiTi;
  src: url(./SourceHanSansCN-Normal.ttf);
}
</style>
